<?php
class index_controller extends common {
	// 退出登录
	function logout() {
		if (isset($_COOKIE['token']))
			delCookie('token');
		
		$this->log('退出登录');
		
		return $this->gotoLogin(0, '退出登录成功！');
	}
	
	// 首页初始化
	function init() {
		$data = array(
			'home' => array(
				'title' => '首页',
				'icon' => 'fa fa-fw fa-home',
				'href' => 'home.html'
			),
			'logo' => array(
				'title' => 'LianYi',
				'image' => 'assets/images/logo.png',
				'href' => ''
			),
			'clear' => 'api.php?c=clearCache',
			'menu' => array()
		);
		
		if (false !== $cache = cache::get('menu')) {
			$data['menu'] = $cache['menu'];
		} else {
			$cte = trim("
				WITH RECURSIVE `cte` AS (
					SELECT * FROM `admin_menu` WHERE `pId` IS NULL AND `status` = 1
					UNION ALL
					SELECT a.* FROM `admin_menu` a
					INNER JOIN `cte` t on a.`pId` = t.`id`
					WHERE a.`status` = 1
				)
			");
			if (false === $rows = $this->sql->cte($cte)->order(array(
				'pId' => 'ASC',
				'order' => 'ASC'
			))->select('cte'))
				return msg(1, '获取数据失败！');
			
			$menu = array2tree($rows);
			
			$data['menu'] = $menu;
			
			cache::set('menu', array(
				'menu' => $menu
			));
		}
		
		$admin = $this->admin;
		unset($admin['pass']);
		
		return msg(0, null, array(
			'data' => $data,
			'admin' => $admin
		));
	}
	
	// 修改基本资料
	function update() {
		$tableName = 'admin_user';
		
		$fields = array(
			'user' => '账号',
			'name' => '姓名',
			'sex' => '性别',
			'birthday' => '生日',
			'mobile' => '手机号码',
			'email' => '邮箱',
			'avatar' => '头像'
		);
		
		$items = filter_post($fields);
		
		if (count($_POST) < 1)
			return msg(1, '参数非法！');
		
		if (!$res = $this->sql->where("`id` = ({$this->admin['id']})")->update($tableName, $_POST)) {
			return msg(2, '修改失败！');
		} else {
			$values = count($_POST) > 1 ? json($_POST, false) : array_shift($_POST);
			
			$this->log('修改资料：' . implode(', ', $items) . "\nid：" . $this->admin['id'] . "\n值：" . $values);
			
			return msg(0, '修改成功！');
		}
	}
	
	// 修改密码
	function update_pass() {
		$tableName = 'admin_user';
		if (!isset($_POST['pass0']) || trim($_POST['pass0']) === '' || !isset($_POST['pass1']) || trim($_POST['pass1']) === '')
			return msg(1, '参数非法！');
		
		if ($this->admin['pass'] !== trim($_POST['pass0']))
			return msg(2, '原密码错误！');
		
		if (!$res = $this->sql->where(array(
			'id' => $this->admin['id'],
			'pass' => trim($_POST['pass0'])
		))->update($tableName, array(
			'pass' => trim($_POST['pass1'])
		))) {
			return msg(3, '修改失败！');
		} else {
			$this->log('修改密码：' . $this->admin['user'] . "\nid：" . $this->admin['id'] . "\n值：" . trim($_POST['pass1']));
			delCookie('token');
			
			return $this->gotoLogin(0, '修改成功！');
		}
	}
	
	// 清除缓存文件
	function clearCache() {
		return deldir(CACHE_PATH) ? msg(0, "清除缓存成功！", array(
			'top' => true
		)) : msg(1, "清除缓存失败！");
	}
}